package com.itheima.demo;

import com.itheima.domain.Person;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhang_Han
 * @version 1.0
 * @date 2020/7/19 18:54
 */
public class Demo_XML_003 {
    public static void main(String[] args) throws Exception {
        //获取解析器对象;
        SAXReader sr = new SAXReader();
        //加载文件;
        Document document = sr.read(new File("demo_xml\\xml\\Person.xml"));
        //读取根标签;
        Element rootElement = document.getRootElement();
        //读取根标签下面的所有子标签;
        List<Element> elements = rootElement.elements("person");

        ArrayList<Person> list = new ArrayList<>();

        for (Element element : elements) {
            //获取属性值 ;
            Attribute idElement = element.attribute("id");
            String id = idElement.getValue();
            String name = element.elementText("name");
            String age = element.elementText("age");
            String tellPhone = element.elementText("tellPhone");
            Person p = new Person(id, name, Integer.parseInt(age), tellPhone);
            list.add(p);
        }
        for (Person person : list) {
            System.out.println(person);
        }
    }
}
